package com.ca.zookeeper.base;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Author Name: Justice
 * Project Name: zookeeper
 * File Name: ZookeeperWatch2
 * Package Name: com.ca.zookeeper.base
 * Date: 2020-02-21 21:43
 * Copyright (c) 2020,All Rights Reserved.
 */


public class ZookeeperWatch2 implements Watcher {
    // JUC中用于阻塞线程的, 可以在多个线程中进行阻塞
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    @Override
    public void process(WatchedEvent event) {
        System.err.println("监听事件执行了");
        // 当连接成功后会执行当前方法, 在此处我们放行即可
        // 事件类型
        Event.EventType type = event.getType();
        // 事件状态
        Event.KeeperState state = event.getState();
        // 成功
        if (state == Event.KeeperState.SyncConnected) {
            switch (type) {
                case None:
                    //NONE代表的是连接操作
                    System.out.println("建立连接成功");
                    // 放行
                    countDownLatch.countDown();
                    break;
                case NodeCreated:
                    String path = event.getPath();
                    System.out.println(path + "结点创建成功");
                    break;
            }
        }
    }

    public static void main(String[] args) throws KeeperException, InterruptedException, IOException {
        ZookeeperWatch2 watch2 = new ZookeeperWatch2();
        ZooKeeper zooKeeper = new ZooKeeper(AddressUtil.ADDRESS, 5000, watch2);
        Stat stat = zooKeeper.exists("/online03", true);
        System.out.println(stat);
        System.in.read();
    }
}
